import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useNavigate } from 'alita';
import {
  Button,
  Card,
  Cascader,
  Checkbox,
  DotLoading,
  Form,
  Input,
  NavBar,
  Radio,
  Space,
  Switch,
  Toast,
} from 'antd-mobile';
import type { CascaderRef } from 'antd-mobile/es/components/cascader';
import { RefObject, useEffect, useState } from 'react';

import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { useModel } from 'alita';
import { AntOutline, RightOutline } from 'antd-mobile-icons';
import styles from './index.less';
const numberFormator = new Intl.NumberFormat();

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  //   const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  type WeiXinUser = {
    userid: string;
    name: string;
  };
  const [weiXinUsers, setWeiXinUsers] = useState<WeiXinUser[]>([]);
  const [clinicalDepartments, setClinicalDepartments] = useState<
    {
      value: string;
      label: string;
      children?: { value: string; label: string }[];
    }[]
  >([]);

  type FieldModal = {
    staffNo: string;
    staffName: string;
  };
  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `新增医护`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 2;
      // 全部没有绑定过的微信用
      fetch(
        `${urlPrefix}/api/doctor-handle/get-wei-xin-user-not-touch-doctor`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<WeiXinUser[]>) => {
                if (code === 0) {
                  if (data) {
                    setWeiXinUsers(data!);
                  }
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });

      // 加载医院及部门
      fetch(
        `${urlPrefix}/api/clinical-department-handle/get-clinical-departments`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                ({
                  data,
                  code,
                  msg,
                }: DetailResult<{ value: string; label: string }[]>) => {
                  if (code === 0) {
                    if (data) {
                      setClinicalDepartments(data!);
                    }
                    setLoadOK(msg);
                  } else {
                    setLoadFails([...loadFails, msg]);
                  }
                },
              )
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK]);

  const onFinish = (values: FieldModal) => {
    // Dialog.alert({
    //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // });
    // return;
    const url = '/api/doctor-handle/create';
    const requestInit: RequestInit = postRequestInit({
      ...values,
      version: 'OK',
    });
    let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<number>) => {
              const { code, msg } = x;
              if (code === 0) {
                //setSuccess(msg);
                Toast.show({ icon: 'success', content: msg });
              } else {
                Toast.show({ icon: 'fail', content: msg });
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
              console.error(`${url} catch in 最内层!`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}[${url}]`);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setIng(false);
        console.log(`finally in 最外层:${url}`);
      });
  };

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            新增检查医生
          </NavBar>
        </DemoBlock>

        <Card
          title={
            <div style={{ fontWeight: 'normal' }}>
              <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
              新增检查医生
            </div>
          }
          extra={<RightOutline />}
          // onBodyClick={onBodyClick}
          // onHeaderClick={onHeaderClick}
          style={{ borderRadius: '16px', margin: '10px' }}
        >
          <div className={styles.content}>
            <Form
              form={form}
              layout={'vertical'}
              onFinish={onFinish}
              footer={
                <>
                  <Button
                    block
                    type="submit"
                    disabled={
                      !authOK ||
                      ing ||
                      fail !== undefined ||
                      success !== undefined
                    }
                    loading={ing}
                    color="primary"
                    size="large"
                  >
                    {success !== undefined ? '已新增' : '提交'}
                  </Button>
                </>
              }
            >
              <Form.Item
                name="clinicalDepartment"
                label="科室"
                onClick={(e: any, ref: RefObject<CascaderRef>) => {
                  console.log(e);
                  console.log(ref);
                  ref.current?.open();
                }}
                rules={[{ required: true, message: '部门科室' }]}
                trigger="onConfirm"
                validateTrigger="onConfirm"
              >
                <Cascader options={clinicalDepartments}>
                  {(items) => {
                    return items.every((item) => item === null)
                      ? '未选择'
                      : items.map((item) => item?.label ?? '未选择').join('-');
                  }}
                </Cascader>
              </Form.Item>

              <Form.Item
                name="weiXinUser"
                label={'医生同时是企业微信用户'}
                rules={[{ required: false, message: '医护' }]}
              >
                <Radio.Group>
                  <Space direction={'vertical'}>
                    {weiXinUsers.map(({ userid, name }) => (
                      <Radio key={userid} value={userid}>
                        {name}
                      </Radio>
                    ))}
                  </Space>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="standards"
                label={'医生权限'}
                rules={[{ required: true, message: '医护' }]}
              >
                <Checkbox.Group>
                  <Space direction={'vertical'}>
                    {[
                      { id: 'doCheckDoctor', name: '检查医生' },
                      { id: 'writeReportDoctor', name: '报告医生' },
                      { id: 'ratifyDoctor', name: '审核医生' },
                    ].map(({ id, name }) => (
                      <Checkbox key={id} value={id}>
                        {name}
                      </Checkbox>
                    ))}
                  </Space>
                </Checkbox.Group>
              </Form.Item>

              <Form.Item
                name="staffName"
                label={'姓名'}
                rules={[{ required: true, message: '姓名' }]}
              >
                <Input maxLength={200} />
              </Form.Item>

              <Form.Item
                name="staffNo"
                label={'工号'}
                rules={[{ required: true, message: '工号' }]}
              >
                <Input maxLength={50} />
              </Form.Item>

              <Form.Item
                name="allowSameNo"
                label="允许工号重复"
                childElementPosition="right"
              >
                <Switch />
              </Form.Item>

              <Form.Item
                name="telephone"
                label={'电话'}
                rules={[{ required: false, message: '电话' }]}
              >
                <Input maxLength={200} />
              </Form.Item>
            </Form>
          </div>
        </Card>
      </Content>
    </Page>
  );
};
